package com.lenovo.server.vote.serverlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;

import com.lenovo.server.utils.HibDB;
import com.lenovo.server.vote.bean.Option;
import com.lenovo.server.vote.bean.Topic;
import com.lenovo.server.vote.bean.VoteUser;

public class VoteServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	private void queryTopic(HttpServletRequest request,
			HttpServletResponse response) {
		List<Topic> topics = HibDB.queryTopic();
		System.out.println("topics is " + topics);
		generalJason(request, response, topics);
	}

	private void vote(HttpServletRequest request, HttpServletResponse response) {
		try {
			String imei = request.getParameter("imei");
			String result = request.getParameter("result");
			System.out
					.println("imei is : " + imei + "\n result is : " + result);
			request.setAttribute("message", "server result");
			request.getRequestDispatcher("/result.jsp").forward(request,
					response);
			// generalJason();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("do get >>>");
		String method = request.getParameter("method");
		if ("vote".equalsIgnoreCase(method)) {
			vote(request, response);
		}
		if ("queryresult".equalsIgnoreCase(method)) {
			queryresult(request, response);
		}
		if ("gettopic".equalsIgnoreCase(method)) {
			queryTopic(request, response);
		}
		if("commit".equalsIgnoreCase(method)){
			
			commit(request,response);
		}
	}

	private void commit(HttpServletRequest request, HttpServletResponse response) {
		String optionName = request.getParameter("option_name");
		String optionId = request.getParameter("option_id");
		String ime = request.getParameter("ime");
		String topicid = request.getParameter("topicid");
		System.out.println("optionName " + optionName + "\n " + 
		"optionId " + optionId + "\n" + 
		"ime " + ime
		);
		
		List<VoteUser> lists = HibDB.getAllUser();
		for(int i = 0;i < lists.size(); i++){
			VoteUser u = lists.get(i);
			if(u.getIME() == null){
				continue;
			}
			if(ime.equals(u.getIME()))
			{
				if(topicid.equals(u.getTopics().getId())){
					System.out.println("�Ѿ�Ͷ��Ʊ������");
					
					try {
						PrintWriter output = response.getWriter();
						output.print("�Ѿ�Ͷ��Ʊ��");
						output.flush();
						output.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				} else{
					Option option = new Option();
					option.setName(optionName);
					option.setId(Integer.parseInt(optionId));
					u.setOptions(option);
					option.getUser().add(u);
					HibDB.save(u);
				}
			}
			
		}
	}


	private void queryresult(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			request.setAttribute("message", "query result ok!!!!");
			request.getRequestDispatcher("/result.jsp").forward(request,
					response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void generalJason(HttpServletRequest request,
			HttpServletResponse response, List<Topic> list) {
		JsonConfig config = new JsonConfig();
		config.setJsonPropertyFilter(new PropertyFilter() {
			public boolean apply(Object source, String name, Object value) {
				if (name.equals("options")) {
					// ������д��Ҫ���˵�������
					return true;
				}
				return false;
			}
		});
		
		JSONObject array = JSONObject.fromObject(list.get(0));
		
//		for(int i = 0; i < array.size() ;i ++){
//			JSONObject obj = (JSONObject) array.get(i);
//			JSONArray optonArray = new JSONArray();
//			Set<Option> sets = list.get(i).getOptions();
//			for (Option option : sets) {
//				optonArray.add(option);
//			}
//			obj.put("option",optonArray);
//		}
		
		System.out.println(array .toString());
		try {
			PrintWriter output = response.getWriter();
			output.print(array.toString());
			output.flush();
			output.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	// private void generalJason(HttpServletRequest request, HttpServletResponse
	// response, List<Topic> list){
	// //
	// [{id:12,title:"xxxx",timelength:28},{id:12,title:"xxxx",timelength:28},
	// {id:12,title:"xxxx",timelength:28}]
	//			
	// StringBuilder json = new StringBuilder();
	// json.append('[');
	// for(Topic voter : list){
	// json.append('{');
	// json.append("id:").append(voter.getId()).append(',');
	// json.append("title:\"").append(voter.getName()).append("\"");
	// json.append("}");
	// }
	// json.append(']');
	//			
	// try {
	// PrintWriter output = response.getWriter();
	// output.print(json.toString());
	// output.flush();
	// output.close();
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// }

}
